# -*- coding: utf-8 -*-
"""
author : heting
date : 2018/6/11 15:37
desc : 数据可视化后台
"""
import time
import base64
import requests
from bs4 import BeautifulSoup as BS
from collections import OrderedDict
import pandas as pd
import datetime
import json
from traceback import format_exc
from io import BytesIO
import re
import codecs
import os
import pymysql
import numpy as np
import xlwt
from pandas import DataFrame,Series
from sqlalchemy import create_engine
import xlrd
from xlutils.copy import copy
from calendar import monthrange
from random import choice,randint
import hashlib
from sqlalchemy.types import *
from MyComFiles.qiYuan.qydata.db.getUserData import *
from flask import Flask,render_template,request,session,redirect,url_for
from flask_session import Session
from redis import Redis

app = Flask(__name__)
# set the secret key.  keep this really secret:
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'

#自定义设置session的有效期 默认一周
app.config['PERMANENT_SESSION_LIFETIME'] = datetime.timedelta(days=7)

SESSION_TYPE = 'redis'
app.config['SESSION_TYPE'] = SESSION_TYPE
# app.config['SESSION_REDIS'] = Redis(host='localhost',port='6379')
app.config['SESSION_REDIS'] = Redis(host='172.16.0.27',port='6379')
Session(app)
# 指定基础模板-对应不同的权限
# baseTemp = {}

# @app.route('/')
# def hello_world():
#     return render_template('t.html')

@app.route('/getJson',methods=['POST'])
def getJson():
    data = {'msg':''}
    try:
        a = request.get_data()
        s = request.form
        print('a = ',a)
        print('s = ', s)
        """判断body是map"""
        if len(s):
            # print('11111111')
            reqObj = request.form
        else:
            # print('222222')
            reqObj = json.loads(a.decode())

        name = reqObj['name']
        if name == 'caotao':
            data = json.dumps({'name': 'yes'})
        else:
            data = json.dumps({'name': name})
    except:
        data['msg'] = '请求参数错误!'
        return data
    return data

@app.route('/dataMap')
def dataMap():
    return render_template('dataMap.html')


@app.route('/login',methods=['GET', 'POST'])
def login():
    session.pop('token', None)
    session.pop('login', None)
    message = None
    if request.method == 'POST':
        loginInfo = request.form.to_dict()
        print('username = ', loginInfo['username'])
        data = loginCheck(loginInfo)
        if data['status']:
            session['token'] = data['token']
            session['login'] = True
            session['username'] = loginInfo['username']
            #print('session = ',session)

            session['v'] = choice(['v1','v1'])
            return redirect(url_for('index'))
        else:
            message =  data['msg']
            return render_template('login.html', message=message)
    return render_template('login.html',message = message)


@app.route('/logout')
def logout():
    session.pop('token', None)
    session.pop('v', None)
    session['login'] = False
    return redirect(url_for('login'))

@app.route('/temptest')
def temptest():
    user = {'nickname':'heting'}
    posts = [{'author':{'nickname':'heting'},'body':'you are my all!'}]
    title = 'hello'
    return render_template('demo.html',user=user,posts=posts,title=title)

"""引导页"""
@app.route('/')
def index():
    if tokenCheck(session):
        data = getOper_OrderData()
        htmlFile = '%s/oper_orderperCnt.html'%session['v']
        return render_template(htmlFile, item=data['data'], showList=data['showList'],len=data['len'])
    return redirect(url_for('login'))


"""运营数据-审批通过率"""
@app.route('/Oper/approvalPassRate')
def approvalPassRate():
    if tokenCheck(session):
        data = getOperData()
        htmlFile = '%s/oper_approvalPassRate.html' % session['v']
        return render_template(htmlFile,data=data['data'],showList=data['showList'],len=data['len'])
    return redirect(url_for('login'))


"""运营数据-进件量"""
@app.route('/Oper/approvalCnt')
def approvalCnt():
    if tokenCheck(session):
        data = getOperData()
        htmlFile = '%s/oper_approvalCnt.html' % session['v']
        return render_template(htmlFile,data=data['data'],showList=data['showList'],len=data['len'])
    return redirect(url_for('login'))


"""运营数据-放款-叠加"""
@app.route('/Oper/approvalAmount')
def approvalAmount():
    if tokenCheck(session):
        data = getOperData()
        htmlFile = '%s/oper_approvalAmount.html' % session['v']
        return render_template(htmlFile,data=data['data'],showList=data['showList'],len=data['len'])
    return redirect(url_for('login'))


"""运营数据-放款"""
@app.route('/Oper/approvalLoan')
def approvalLoan():
    if tokenCheck(session):
        data = getOperData()
        htmlFile = '%s/oper_approvalLoan.html' % session['v']
        return render_template(htmlFile,data=data['data'],showList = data['showList'],len=data['len'])
    return redirect(url_for('login'))

"""运营数据-放款-件均"""
@app.route('/Oper/approvalPer')
def approvalPer():
    if tokenCheck(session):
        data = getOperData()
        htmlFile = '%s/oper_approvalPer.html' % session['v']
        return render_template(htmlFile,data=data['data'],showList = data['showList'],len=data['len'])
    return redirect(url_for('login'))


"""运营数据-作业产能"""
@app.route('/Oper/orderperCnt')
def orderPerCnt():
    if tokenCheck(session):
        data = getOper_OrderData()
        htmlFile = '%s/oper_orderperCnt.html' % session['v']
        return render_template(htmlFile,item=data['data'],showList = data['showList'],len=data['len'])
    return redirect(url_for('login'))

"""风控数据-账龄分析-月末"""
@app.route('/risk/aging/month')
def risk_aging():
    if tokenCheck(session):
        data = get_risk_aging()
        htmlFile = '%s/risk_aging.html' % session['v']
        return render_template(htmlFile,item=data['data'],showList = data['showList'],len=data['len'])
    return redirect(url_for('login'))


"""风控数据-账龄分析-期末"""
@app.route('/risk/aging/term')
def risk_agingxc():
    if tokenCheck(session):
        data = get_risk_agingxc()
        htmlFile = '%s/risk_agingxc.html' % session['v']
        return render_template(htmlFile,item=data['data'],showList = data['showList'],len=data['len'])
    return redirect(url_for('login'))


if __name__ == '__main__':
    port = '80'
    print('http://172.16.3.119:' + port + '/')
    app.run(host='0.0.0.0',port=port,debug=True)
